package com.edmond.controller;

import com.edmond.entity.Admin;
import com.edmond.entity.User;
import com.edmond.feign.AccountFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.xml.ws.http.HTTPBinding;
import java.util.LinkedHashMap;

@Controller
@RequestMapping("/account")
public class AccountHandler {
    @Autowired
    private AccountFeign accountFeign;

    @PostMapping("/login")
    public String login(@RequestParam("username") String username, @RequestParam("password") String password, @RequestParam("type") String type, HttpSession session) {
        Object account = accountFeign.login(username, password, type);
        //  对获取的结果进行强制类型转换（回传之后的数据类型是 LinkedHashMap 类型）
        LinkedHashMap<String,Object> hashMap = (LinkedHashMap<String, Object>) account;
        String result = null;
        String idStr = null;
        long id = 0L;
        if (account == null) {
        } else {
            switch (type) {
                case "user":
                    User user = new User();
                    idStr = hashMap.get("id")+"";    //  获取用户的 id 并转换成 String类型
                    id = Long.parseLong(idStr);
                    String nickname = (String) hashMap.get("nickname");
                    user.setId(id);
                    user.setNickname(nickname);
                    session.setAttribute("user",user);
                    result = "index";
                    break;
                case "admin":
                    Admin admin = new Admin();
                    idStr = hashMap.get("id")+"";    //  获取用户的 id 并转换成 String类型
                    id = Long.parseLong(idStr);
                    String username2 = (String) hashMap.get("username");
                    admin.setId(id);
                    admin.setUsername(username2);
                    session.setAttribute("admin",admin);
                    result = "main";
                    break;
            }
        }
        return result;
    }

    //  当前用户退出登录
    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "redirect:/login.html";
    }

}
